package com.sike.netty.im.server.handler;

import com.sike.netty.im.server.service.BeanFactory;
import com.sike.netty.im.server.service.SessionService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务端空闲检测 handler
 *
 * @author chenssy
 * @date 2023/09/24
 */
@Slf4j
public class ImIdleStateHandler extends IdleStateHandler {
    private static final int READER_IDLE_TIME = 10;
    public ImIdleStateHandler() {
        super(READER_IDLE_TIME, 0, 0);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx,msg);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) {
        log.warn("连接{}已有 {} 秒未读到数据，关闭连接",ctx.channel(),READER_IDLE_TIME);

        // 解除绑定
        SessionService sessionService = (SessionService) BeanFactory.getServiceBean(SessionService.class);
        String userId = sessionService.getUserIdByChannel(ctx.channel());
        sessionService.unBind(ctx.channel(),userId);

        // 关闭连接
        ctx.channel().close();
    }
}
